<template>
  <div id="versionInfo">
    <!-- 头部 -->
    <BaseHeader :title="$t('translate10')" :rightIcon="null" @leftClick="$router.goBack()" />
    <div class="navBar" style="width: 100%; height: 56px" :style="{ paddingTop: `${headerHeight}px` }">
      <van-tabs v-model="active" :color="tabColor" style="height: 56px; margin-top: 5px" @click="handle">
        <van-tab :title="$t('translate13')" name="d"></van-tab>
        <van-tab :title="$t('translate15')" name="m"></van-tab>
        <van-tab :title="$t('translate14')" name="y"></van-tab>
      </van-tabs>
    </div>
    <div class="timeSelect">
      <div class="timeTitle">
        <div class="leftArrow" :style="{ backgroundImage: `url(${leftIcon}) ` }" @click="handlLeft"></div>
        <div class="centerText">
          <span>
            {{ titleDate }}
          </span>
          <!-- <span
            >2022{{ $t("year") }}09{{ $t("month") }}09{{ $t("day") }}
            {{ $t("Monday") }}</span
          > -->
        </div>
        <div class="rightArrow" :style="{ backgroundImage: `url(${rightIcon}) ` }" @click="handlRight"></div>
      </div>
      <div class="nowTime">{{ titleTime }}</div>
      <div class="timeData">
        {{ $t("translate29") }}<span style="margin:0 2px;">{{ countSet }}</span>{{ $t("second") }}
      </div>
    </div>
    <charBarStack :data="dataBar" ref="charBar"></charBarStack>
    <div class="title titleSecond">{{ $t("translate17") }}</div>
    <HomeInfo :dataList="dataList"></HomeInfo>
    <div class="title titleSecond">{{ $t("translate10") }}</div>
    <charPie :data="dataPie" ref="charPie"></charPie>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import charBarStack from "@/components/charBarStack.vue";
import charPie from "@/components/charPie.vue";
import HomeInfo from "@/components/HomeInfo.vue";
import mixin from "@/mixins/mixins";
import { generateWifiPromise } from "@/util/index.js";
export default {
  name: "VersionInfo",
  mixins: [mixin],
  data() {
    return {
      active: 0,
      rightIconName: "ic_list_right",
      leftIconName: "ic_list_left",
      countSet: 0,
      dataList: [
        {
          number: 11,
          unit: "",
          infoName: this.$t("translate22"),
        },
        {
          number: 37.6,
          unit: "%",
          infoName: this.$t("translate23"),
        },
      ],
      dataPie: [
        { value: 0, name: this.$t("enum2") },
        { value: 0, name: this.$t("enum3") },
        { value: 0, name: this.$t("enum4") },
        { value: 0, name: this.$t("enum5") },
      ],
      dataBar: [[], [], [], [], []],
    };
  },
  components: {
    charBarStack,
    HomeInfo,
    charPie,
  },
  computed: {
    list() {
      return [
        {
          // 固件版本
          id: 0,
          left: this.$t("fwVersion"),
          right: this.fwv,
          arrow: false,
        },
        {
          // 硬件版本
          id: 1,
          left: this.$t("hwVersion"),
          right: this.hwv,
          arrow: false,
          border: false,
        },
      ];
    },
    ...mapState(["fwv", "hwv", "darkMode", "devId", "seatedCountThis"]),
    ...mapGetters(["imgPath", "headerHeight"]),
    rightIcon() {
      return this.darkMode
        ? require(`../assets/${this.rightIconName}_Dark.png`)
        : require(`../assets/${this.rightIconName}_normal.png`);
    },
    leftIcon() {
      return this.darkMode
        ? require(`../assets/${this.leftIconName}_Dark.png`)
        : require(`../assets/${this.leftIconName}_normal.png`);
    },
  },
  watch: {
    titleDate: {
      handler(newVal, oldVal) {
        this.getData(this.startTime, this.endTime, this.dateType);
        this.getBarData(this.startTime, this.endTime, this.dateType);
      },
    },
    type: {
      handler(newVal, oldVal) {
        if (newVal == "d") {
          this.dataList[0].infoName =
            this.$t("translate35") + this.$t("translate22");
          this.dataList[1].infoName =
            this.$t("translate35") + this.$t("translate23");
        } else if (newVal == "m") {
          this.dataList[0].infoName =
            this.$t("translate36") + this.$t("translate22");
          this.dataList[1].infoName =
            this.$t("translate36") + this.$t("translate23");
        } else {
          this.dataList[0].infoName =
            this.$t("translate37") + this.$t("translate22");
          this.dataList[1].infoName =
            this.$t("translate37") + this.$t("translate23");
        }
      },
      immediate: true
    },
  },
  methods: {
    getData(startTime, endTime, dateType) {
      let p1 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "sittingcount1",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: "DAILY",
          }),
        ],
        callback: "callback1",
      });
      let p2 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "sittingcount2",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: "DAILY",
          }),
        ],
        callback: "callback2",
      });
      let p3 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "sittingcount3",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: "DAILY",
          }),
        ],
        callback: "callback3",
      });
      let p4 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "sittingcount4",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: "DAILY",
          }),
        ],
        callback: "callback4",
      });

      Promise.all([p1, p2, p3, p4])
        .then((result) => {
          console.log("result", result); //['成功了', 'success']

          for (let i = 0; i < result.length; i++) {
            this.dataPie[i].value = 0;
            result[i].devDatas.forEach((e) => {
              this.dataPie[i].value += parseInt(e.sum);
            });
          }
          console.log("this.dataPie:", this.dataPie);

          this.dataList[0].number = this.$t("enum1");
          let max = 0;
          let all = 0;
          this.dataPie.forEach((e) => {
            all = all + e.value;
            if (e.value > max) {
              max = e.value;

              this.dataList[0].number = e.name;
            }
          });
          console.log("最大", max);
          console.log("总数", all);
          this.dataList[1].number = (isNaN(((max / all) * 100).toFixed(2)) ? 0 : ((max / all) * 100).toFixed(2));
          this.$refs.charPie.draw();
          this.countSet = all
        })
        .catch((error) => {
          console.log("报错了");
          console.log(error);
        });
    },
    getBarData(startTime, endTime, dateType) {
      let p1 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "eventTime1",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: dateType,
          }),
        ],
        callback: "callback11",
      });
      let p2 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "eventTime2",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: dateType,
          }),
        ],
        callback: "callback22",
      });
      let p3 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "eventTime3",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: dateType,
          }),
        ],
        callback: "callback33",
      });
      let p4 = generateWifiPromise({
        method: "getDevStatisticsDataWithQuery",
        params: [
          this.devId, // devid,string,请取"0"，表示当前设备，暂不支持其它取值
          JSON.stringify({
            devId: this.devId,
            sid: "eventTime",
            character: "eventTime4",
            startTime: startTime,
            endTime: endTime,
            pageSize: "31",
            accuracy: dateType,
          }),
        ],
        callback: "callback44",
      });

      Promise.all([p1, p2, p3, p4])
        .then((result) => {
          console.log("坐姿切换统计result", result); //['成功了', 'success']
          let count = 0;
          let xarr = [];
          let yarr = [[], [], [], []];
          if (this.type == "d") {
            for (let i = 0; i < 25; i++) {
              let day2 = "";
              // seatingtime = 0;
              if (i < 10) {
                day2 = "0" + i;
                xarr.push("0" + i + ":00");
              } else {
                day2 = i;
                xarr.push(i + ":00");
              }

              for (let i = 0; i < result.length; i++) {
                let isHave = false;
                let arr = [];
                let sum = 0;
                result[i].devDatas.forEach((e) => {
                  let day = e.time.slice(8, 10);

                  if (day == day2) {
                    isHave = true;
                    sum = e.sum;
                  }
                });
                console.log("填值");
                if (isHave) {
                  yarr[i].push(parseInt(sum));
                  count += parseInt(sum)
                } else {
                  yarr[i].push(0);
                }
              }
            }
            yarr.unshift(xarr);
            this.dataBar = yarr;
          } else if (this.type == "m") {
            var weekArr = [
              this.$t("Monday"),
              this.$t("Tuesday"),
              this.$t("Wednesday"),
              this.$t("Thursday"),
              this.$t("Friday"),
              this.$t("Saturday"),
              this.$t("Sunday"),
            ];
            var weekDay = [];
            for (let x = 0; x < 7; x++) {
              let wd = new Date(
                parseInt(this.startTime + "000") + 24 * 60 * 60 * 1000 * x
              ).getDate();
              weekDay.push(wd);

              for (let i = 0; i < result.length; i++) {
                let isHave = false;
                let arr = [];
                let sum = 0;
                result[i].devDatas.forEach((e) => {
                  let day = e.time.slice(6, 8);
                  console.log("填值1");
                  if (day == wd) {
                    console.log("填值2");
                    isHave = true;
                    sum = e.sum;
                  }
                });
                console.log("填值");
                if (isHave) {
                  yarr[i].push(parseInt(sum));
                  count += parseInt(sum)
                } else {
                  yarr[i].push(0);
                }
              }
            }

            xarr = weekArr;
            yarr.unshift(xarr);
            this.dataBar = yarr;
          } else {
            for (let i = 1; i < this.mouthDay + 1; i++) {
              let day2 = "";
              if (i < 10) {
                day2 = "0" + i;
                xarr.push("0" + i);
              } else {
                day2 = i;
                xarr.push(i);
              }
              for (let i = 0; i < result.length; i++) {
                let isHave = false;
                let arr = [];
                let sum = 0;
                result[i].devDatas.forEach((e) => {
                  let day = e.time.slice(6, 8);

                  if (day == day2) {
                    isHave = true;
                    sum = e.sum;
                  }
                });

                if (isHave) {
                  yarr[i].push(parseInt(sum));
                  count += parseInt(sum)
                } else {
                  yarr[i].push(0);
                }
              }
            }

            yarr.unshift(xarr);

            this.dataBar = yarr;
          }

          // for (let i = 0; i < result.length; i++) {
          //   let arr = [];
          //   result[i].devDatas.forEach((e) => {
          //     arr.push(parseInt(e.sum));
          //   });
          //   this.dataBar.push(arr);
          // }
          // console.log("日yarr", yarr);
          // console.log("this.dataBar", this.dataBar);
          // this.dataBar = yarr;

          this.$refs.charBar.draw();
        })
        .catch((error) => {
          console.log(error);
        });



    },
  },
  created() {
    window.hilink.setTitleVisible(false, "window.Ag.setTitleVisible");
    window.Ag.setTitleVisible = (res) => { };
    // 重置物理返回键
    window.goBack = () => {
      if (this.popupShow) {
        this.popupShow = 0;
        return;
      }
      this.$router.goBack();
    };
  },
};
</script>
<style lang="less" scoped>
@import url("../style/public.less");

// 适配
.pad {
  #versionInfo {
    .content {
      margin: 0 var(--pad_column_1);
    }
  }
}
</style>